# -*- coding: utf-8 -*-

from abc import ABC, abstractmethod
import requests
import hashlib
import random
import string
import yaml


class Translation(ABC):
    @abstractmethod
    def translation(self, text):
        pass

class BAIDUTranslation(Translation):
    def __init__(self):

        self.language = None
        self.transprofile = None
        self.trans = None
        self.url = None
        self.secret = None
        self.appid = None
        self.profile = None
        self.update()

        self.session = requests.Session()
        self.session.trust_env = False

    def update(self):
        with open("BaiduTranslate.yaml", 'r', encoding='utf-8') as f:
            self.profile = yaml.safe_load(f)
        with open("config.yaml", 'r', encoding='utf-8') as f:
            self.transprofile = yaml.safe_load(f)
        self.appid = self.profile.get("baidu_app_id")
        self.secret = self.profile.get("baidu_secret")
        self.url = self.profile.get("baidu_translation_url")
        self.trans = self.transprofile.get("translate")
        if self.trans == 0:
            self.language = 'en'
        else:
            self.language = 'zh'

    def translation(self, text):
        headers = {
            "content-type": "application/x-www-form-urlencoded"
        }
        data = {
            "q": text,
            "from": 'auto',
            "to": self.language,
            "appid": self.appid,
            "salt": "",
            "sign": ""
        }

        if not text:
            return "Unspecified content"

        salt = self.generate_random_string(6)
        data["salt"] = salt
        data["sign"] = self.generate_sign(data)

        try:
            response = self.session.post(url=self.url, data=data, headers=headers)
            response.raise_for_status()  # 检查响应状态码
            response_data = response.json()
            if response_data.get("error_code"):
                return f"调用百度翻译出错，返回错误代码为: {response_data.get('error_code')}"

            translation_result = [result.get("dst") for result in response_data.get("trans_result", [])]
            translated_answer="\n".join(translation_result)
            return translated_answer
        except requests.RequestException as e:
            return f"调用翻译请求时出现网络错误: {e}"
        except ValueError as e:
            return  f"解析响应数据时出现错误: {e}"
        except Exception as e:
            return f"调用翻译请求时出现未知错误: {e}"

    def generate_sign(self, data):
        sign_str = f"{data.get('appid')}{data.get('q')}{data.get('salt')}{self.secret}"
        return self.generate_md5(sign_str)

    def generate_md5(self, content):
        if content:
            md5_hash = hashlib.md5()
            md5_hash.update(content.encode("utf-8"))
            return md5_hash.hexdigest().lower()
        return None

    @staticmethod
    def generate_random_string(length=6):
        chars = string.ascii_letters + string.digits
        return ''.join(random.choices(chars, k=length))
